#! /bin/bash

usage()
{
    echo "Usage: gocd hostname -l localdir -r remotedir"
}

checkhost()
{
    tmp=`grep "^$1 " $config | sed -n 1p`
    if [ -z "$tmp" ];then
        echo "$1 not configured in /etc/goto.conf"
        exit 2
    fi
    hostname=$1
}

formatdir()
{
    tmp=`echo $1 |grep "^[/~]"`
    if [ -z "$tmp" ];then
        ret="~/$1"
    else
        ret="$1"
    fi

    tmp=`echo $ret | grep "/$"`
    if [ -z "$tmp" ];then
        ret="$ret/"
    fi
}

checkdir()
{
    if [ $1 = "-l" ];then
        localdir=$2
        if [ -z "$3" ];then
            remotedir="~/"
        elif [ "$3" = "-r" ];then
            remotedir=$4
        else
            usage
            exit 1
        fi
    else
        remotedir=$2
        if [ -z "$3" ];then
            localdir="~/"
        elif [ "$3" = "-l" ];then
            localdir=$4
        else
            usage
            exit 1
        fi
    fi

    formatdir $localdir
    localdir=$ret
    formatdir $remotedir
    remotedir=$ret
}

modifyconf()
{
    if [ ! -f $gocdconf ];then
        echo $1 $2 $3 >> $gocdconf
        return
    fi

    tmp=`grep "^$1 " $gocdconf`
    if [ -z "$tmp" ];then
        echo $1 $2 $3 >> $gocdconf
    else
        sed "s#^$1 .*#$1 $2 $3#g" $gocdconf > .tmp
        mv .tmp $gocdconf
    fi
}

gocdconf=/etc/goto.conf.d/gocd.conf
config=/etc/goto.conf

if [ $# -ne 3 -a $# -ne 5 ];then
    usage
    exit 1
else
    if [ $2 != "-l" -a $2 != "-r" ];then
        usage
        exit 1
    fi
fi

checkhost $1
checkdir $2 $3 $4 $5
modifyconf $hostname $localdir $remotedir

